package com.hz.qs.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.hz.qs.dao.UserInfoDao;
import com.hz.qs.model.UserInfo;
import com.hz.qs.model.YiActiveRoom;
import com.hz.qs.utils.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.hz.qs.utils.Common.*;

@Service
@Slf4j
public class LoginService {

    @Autowired
    private UserInfoDao userInfoDao;

    /**
     * 登录处理函数
     *
     * @param httpSession
     * @param userName
     * @param password
     * @return com.hz.qs.utils.RestResult
     * @author yejy
     * @date 2020/11/2 09:43
     */
    public RestResult loginOpt(HttpSession httpSession, String userName, String password) {
        String md5 = SecureUtil.md5(password);
        Map<String, Object> map = new HashMap<>(2);
        List<UserInfo> userInfoList = userInfoDao.selectLoginByNameAndPw(userName, md5);
        if (userInfoList.isEmpty()) {
            return RestResult.failResult("账号或者密码错误！", 500);
        } else {
            UserInfo userInfo = userInfoList.get(0);
            //如果是医生需要插入activeroom表，防止出现医生重复登录
            if (DOC_STATE.equals(userInfo.getIdDiff())) {
                String s = LocalDate.now() + START_TIME;
                String e = LocalDate.now() + END_TIME;
                List<YiActiveRoom> activeList = userInfoDao.getActiveRoomByDocId(userInfo.getUserCode(), s, e);
                if (activeList.size() > 0) {
                    return RestResult.failResult("不能重复登录！", 500);
                } else {
                    userInfo.setActiveId(IdUtil.fastSimpleUUID());
                    userInfoDao.insertActiveRoom(userInfo);
                }
            }
            httpSession.setAttribute("userInfo", userInfo);
            return RestResult.successResult(userInfo);
        }
    }

    public void logout(HttpSession httpSession) {
        UserInfo userInfo = (UserInfo) httpSession.getAttribute("userInfo");
        Integer idDiff = Optional.ofNullable(userInfo.getIdDiff()).orElse(-1);
        if (DOC_STATE.equals(idDiff)) {
            userInfoDao.updateActiveRoom(userInfo);
        }
        httpSession.removeAttribute("userInfo");
    }
}
